import axios from 'axios'

import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'
import router from '@/router'

const service = axios.create({
    timeout: 15000 // request timeout
})


service.interceptors.request.use(
    config => {
        config.headers['token'] = getToken()
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    (resp) => {
        return resp
    },
    error => {
        const {status} = error.response
        if (status === 401) {
            /**
             * token过期
             */
            MessageBox.confirm('登录状态已过期，请重新登录！', '提示', {
                confirmButtonText: '前去登录',
                cancelButtonText: '浏览其他',
                type: 'warning'
            }).then(() => {
                router.push("/login").then(r => {})
            }).catch(() => {
                router.push("/").then(r => {})
            }).finally(() => {
                store.dispatch("app/logout").then(r => {})
            })
        }
        return Promise.reject(new Error('登录状态已过期，请重新登录！'))
    }
)

export default service
